<?php

class Controller_Search extends Controller_Base
{
	public $Split_Word_Blank = array();
	
	public function __construct($parts) {		
		$this->parts        = $parts;
		$this->common_vars  = Registry::get("common_vars");
		$this->table_module = PRFX."search";
		$this->table_index  = PRFX."indexes";
		$this->q = $_POST["q"];
	}
	
	private function write_stat($total_rows = 0)
	{
		$text_search = mysql_escape_string($this->q);		
		$r =& Registry::get("MDB")->query("SELECT * FROM `".$this->table_module."` WHERE `String`='".$text_search."' LIMIT 1;");		
		if (PEAR::isError($r)) {
			die($r->getMessage().' ::: '.$r->getUserInfo());
		}		
		if($r->numRows()) {
			$p = $r->fetchRow(MDB2_FETCHMODE_ASSOC);
			$query = "UPDATE `".$this->table_module."` SET `Count`='".($p['count'] + 1)."',`Results`='".$total_rows."' WHERE `String`='".$text_search."';";			
		} 
		else {
			$query = "INSERT INTO `".$this->table_module."` VALUES ('', '".$text_search."', '1', '".$total_rows."');";		
		}		
		$r =& Registry::get("MDB")->query($query);		
		if (PEAR::isError($r)) {
			die($r->getMessage().' ::: '.$r->getUserInfo());
		}
	}
	
	public function filter()
	{		
		if(!empty($this->q)) {
			preg_match("/^[а-яА-Яa-zA-Z0-9ъЪЬьЁё_ -]{1,300}/iu", $this->q, $string);			
			$q = trim($string[0]);
			$q = preg_replace('/  +/', ' ', $q);
			$this->text_search = trim($q);	
			$_SESSION['q'] = $this->text_search;			
		}
		elseif(!empty($_SESSION['q'])) {			
			$this->text_search = $_SESSION['q'];			
		}
	}
	
	private function create_query($string)
	{			
		$Split_Word_Blank = mb_split("[[:blank:]]+", $string);						
		$stopWords = array(":", "=", "|", ".", "-", "+", ",", "%", "?", "(", ")", "*", "+", "/", "!", 
		"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "^", "_", "«", "a","без","более","бы","был",
		"была", "были", "было", "быть", "в", "вам", "вас", "весь", "во", "вот", "все", "всего", "всех", 
		"вы", "где", "да", "даже", "для", "до", "его", "ее", "если", "есть", "ещё", "же", "за", "здесь", 
		"и", "из", "из-за", "или", "им", "их", "к", "как", "как-то", "ко", "когда", "кто", "ли", "либо", 
		"мне", "может", "мы", "на", "надо", "наш", "не", "него", "неё", "нет", "ни", "них", "но", "ну", "о", 
		"об", "однако", "он", "она", "они", "оно", "от", "очень", "по", "под", "при", "с", "со", "так", "также", 
		"такой", "там", "те", "тем", "то", "того", "тоже", "той", "только", "том", "ты", "у", "уже", "хотя", 
		"чего", "чей", "чем", "что", "чтобы", "чьё", "чья", "эта", "эти", "это", "я");				
		foreach($Split_Word_Blank as $key => $word) {			
			if(!empty($word) && !in_array($word, $stopWords)) {
				$Query_String[] = " (`Title` LIKE '%".$word."%' OR `Text` LIKE '%".$word."%')";
				$this->Split_Word_Blank[] = $word;
			}			
		}
		if(!empty($Query_String)) {
			return implode(" OR ", $Query_String);
		}
	}
	
	private function yes_no_in_mas($split_string_array, $word)
	{
		$new_mas = array();
		$value = mb_strtolower($word, mb_detect_encoding($word));		
		foreach($split_string_array as $k => $v)
		{
			$val = mb_strtolower($v, mb_detect_encoding($v));
			$split_string_array_new[] = $val;			
			if(similar_text($val, $value) == mb_strlen($value, mb_detect_encoding($value))) {
				return true;
			}
		}
		if(in_array($value, $split_string_array_new)) {
			return true;	
		}		
	}
	
	private function redd($string)
	{
		$format_text = mb_ereg_replace("[[:blank:]]+", " ", $string);
		$format_text = trim($format_text);		
		$split_string_array = mb_split("[[:blank:]]+", $format_text);	
		$lower_string = mb_strtolower($format_text, mb_detect_encoding($format_text));
		
		//print_r($split_string_array);
			
		if(!empty($this->Split_Word_Blank))
		{
			foreach($this->Split_Word_Blank as $word)
			{				
				if(self::yes_no_in_mas($split_string_array, $word))
				{				
					$min = mb_strpos($lower_string, $word, 0, mb_detect_encoding($lower_string));
					if($min < 100) {
						$min = 0;
						$n = '';
					}
					elseif($min >= 100) {
						$min = $min - 100;
						$n = '...';
					}
				}							
				$format_text = mb_substr($format_text, $min, 250, mb_detect_encoding($format_text));	
				$format_text = mb_ereg_replace(mb_strtolower($word, mb_detect_encoding($word)), '<strong style="color:red;">'.$word.'</strong>', mb_strtolower($format_text, mb_detect_encoding($format_text)));							
			}
		}
		
		return $n.$format_text.$n;
	}
	
    public function out()
	{     
		self::filter();
		$Sql_query = self::create_query($this->text_search);				
		if(!empty($Sql_query)) 
		{			
			$_PAGING = new navygation_page(Registry::get("MDB"), $this->parts[1], $this->parts[3]);
			$r = & $_PAGING->get_page("SELECT * FROM `".$this->table_index."` WHERE ".$Sql_query);
			if(PEAR::isError($r)) {
				die($r->getMessage().' ::: '.$r->getUserInfo());
			}			
			if($r->numRows()) 
			{				
				while($p = $r->fetchRow(MDB2_FETCHMODE_ASSOC))
				{
					$out["cicle"][] = array(
						"url"   => $p['url'],
						"title" => self::redd($p['title']),
						"text"  => self::redd($p['text'])
					);			
				}
			}		
			$out['navygation']['prev'] = $_PAGING->get_prev_page_link();
			$out['navygation']['next'] = $_PAGING->get_next_page_link();
			$out['navygation']['pages'] = $_PAGING->get_page_links();
			$out['navygation']['result_text'] = $_PAGING->get_result_text();			
			
			self::write_stat($_PAGING->total_rows);
			
			//print_r($out);		
		}    
		Registry::set("title", functions::createTitle(array($this->common_vars["structure_name"]), ''));
		
		Registry::get("smarty")->assign($out);
		return Registry::get("smarty")->fetch(TEMPLATE_SITE.$this->common_vars["controller_template"], Registry::get("cache_id"));	
    }
}

$controller = new Controller_Search($parts);
$site_module_out = $controller->out();

?>